<template>
    <base-breadcrumb :title="$route.meta.title">
        <!-- 技术交底编辑 -->
        <a-spin :spinning="loading">
            <a-form-model
                ref="ruleForm"
                :model="form"
                :label-col="{ span: 6 }"
                :wrapper-col="{ span: 18 }"
                :rules="editModel != 0 ? rules : {}"
            >
                <!-- 表格 -->
                <a-card :bordered="false">
                    <title-name title="基本信息"></title-name>
                    <custom-form
                        :formList="formList"
                        :form="form"
                        :editModel="editModel == 0 ? '' : ''"
                        @getOption="getOption"
                        @selectOrg="selectOrg"
                        :isEmit="false"
                    >
                        <!-- 附件上传 -->
                        <template #fileInfoVOSigns>
                            <template v-if="editModel != 0">
                                <l-table businessCode="FACE01" :uploadArrys.sync="form.fileInfoVOSigns"></l-table>
                                <!-- <div class="file_prompt">支持扩展名：.rar .zip .doc .docx .pdf .jpg...</div> -->
                            </template>
                            <file-link v-else :file-list="form.fileInfoVOSigns" style="margin-top: -3px"></file-link>
                        </template>
                        <template #fileInfoVOPictures>
                            <template v-if="editModel != 0">
                                <upload-list
                                    :businessCode="'FACE01'"
                                    uploadType="image"
                                    :editModel="editModel"
                                    :uploadArrys.sync="form.fileInfoVOPictures"
                                    multiple
                                ></upload-list>
                            </template>
                            <template v-else>
                                <span v-if="!form.fileInfoVOPictures || form.fileInfoVOPictures.length < 1">
                                    <empty description="`暂未上传照片`"></empty>
                                </span>
                                <upload-list
                                    v-else
                                    :businessCode="'FACE01'"
                                    uploadType="image"
                                    :editModel="editModel"
                                    :uploadArrys.sync="form.fileInfoVOPictures"
                                    multiple
                                ></upload-list>
                            </template>
                        </template>
                    </custom-form>
                </a-card>

                <!-- 页脚操作栏 -->
                <div class="btn_box page-btn-right-top" v-if="editModel != 0">
                    <a-button
                        v-if="form.status != 1"
                        class="button_right"
                        type="primary"
                        :loading="loading.DRAFT"
                        @click="handleSubmit('DRAFT')"
                        >保存草稿</a-button
                    >
                    <a-button
                        class="button_right"
                        type="primary"
                        :loading="loading.SUBMITTED"
                        @click="handleSubmit('SUBMITTED')"
                        >提交</a-button
                    >
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
                <div class="btn_box page-btn-right-top" v-else>
                    <a-button type="primary" @click="handleActiveClose">关闭</a-button>
                </div>
            </a-form-model>
             </a-spin
        >
    </base-breadcrumb>
</template>

<script>
import {
    addTechnicalDisclosure,
    getTechnicalDisclosureById,
    updateTechnicalDisclosure
} from '@/api/technical/technicalClarificaiton'
import BaseEditPage from '@/views/baseEditPage' // 编辑详情页基础配置
import SelectSubCompany from '@/components/Select/SelectSubCompany' // 分公司
import SelectProject from '@/components/Select/SelectProject' // 分公司
import SelectSubcontractor from '@/components/Select/SelectSubcontractor' // 分包商
import SelectPersonByProject from '@/components/Select/SelectPersonByProject'
import UploadList from '@/components/UploadList'
import SelectTreeSubItem from '@/components/Select/SelectTreeSubItem' // 分部分项
import ASelectOrgPeople from '@/components/Select/ASelectOrgPeople'
import { getProgramList } from '@/api/technical/approval'
import SelectProjectType from '@/components/Select/SelectProjectType' // 工程类别
import { Empty } from 'ant-design-vue'
export default {
    name: 'a' + Date.now(),
    extends: new BaseEditPage(),
    components: {
        UploadList,
        Empty,
        ASelectOrgPeople
    },
    data() {
        return {
            loading: false, // 加载控件
            visible: false, //人员选择控件
            editModel: 0, // 操作状态:0 查看;1 编辑;2 新增
            form: {
              fileInfoVOPictures: [],
              fileInfoVOSigns: [],
              curOrgId: '',
              disclosureUserId:null
            }, // 表单
            id: '',
            subContractorOrgId: '', //分包商组织id
            loadingBtn: {
                DELETE: false,
                DRAFT: false,
                SUBMITTED: false,
                REJECTED: false
            },
            rules: {
                floorName: [{ required: true, message: '请输入' }],
                subItemProjectId: [{ required: true, message: '请选择' }],
                // quantities: [{ required: true, message: '请输入' }],
                subcontractorId: [{ required: true, message: '请选择' }],
                subcontractorLeaderId: [{ required: true, message: '请选择' }],
                disclosureUserId: [{ required: true, message: '请选择' }],
                projectType: [{ required: true, message: '请选择' }],
                disclosureTime: [{ required: true, message: '请选择' }],
                disclosureContent: [{ required: true, message: '请输入' }],
                fileInfoVOSigns: [{ type: 'array', required: true, message: '请上传交底原件', trigger: 'blur' }],
                // fileInfoVOPictures: [{ type: 'array', required: true, message: '请上传附件', trigger: 'blur' }]
            }, // 校验规则
            init: false, // 初始化控件
            SelectOrgId:null,   //单位id
            programList:[], //方案名称
        
        }
    },
    watch: {
        // 监听附件实现附件校验
        'form.fileInfoVOSigns'() {
            if (this.editModel != 0 && this.init) {
                this.$nextTick(() => {
                    this.$refs.ruleForm?.validateField('fileInfoVOSigns')
                })
            }
        },
        // 监听附件实现附件校验
        'form.fileInfoVOPictures'() {
            if (this.editModel != 0 && this.init) {
                this.$nextTick(() => {
                    this.$refs.ruleForm?.validateField('fileInfoVOPictures')
                })
            }
        },
    },
    mounted() {
        this.$route.meta.title = ['技术交底查看', '技术交底编辑', '技术交底新增'][this.editModel]
        // 不为添加时请求详情
        if (this.editModel != 2) {
            this.loading = true
            getTechnicalDisclosureById({ id: this.id })
                .then((res) => {
                    this.loading = false

                    this.form = res.data
                    this.form.curOrgId = this.form.projectId
                    this.getProgramList(this.form.projectId,false)

                    this.$nextTick(() => {
                        this.init = true
                    })
                })
                .catch(() => {
                    this.loading = false
                })
        } else {
            this.$nextTick(() => {
                //this.form.curOrgId = this.$userInfo().currentPost.id
                this.form.disclosureUserId = this.$userInfo().employee.userId;
                this.init = true
            })
        }
        //this.getProgramList();
    },
    computed: {
        formList() {
            return [
              {
                label: '所属单位',
                type: 'orgTree',
                keyName: 'curOrgId',
                rules: [{ required: true, message: '请选择项目名称', trigger: 'change' }],
                span: 16,
                isAutoSelectFirst: true,
                isNeedAuth:true,
                checkStrictly: true,
                disabled:this.editModel == 0 || this.editModel == 1,
                statusSet:[1,2,3,4,5,6],
                isQueryProjecDetail: false
              },
                // {
                //     type: SelectSubCompany,
                //     keyName: 'branchCompanyId',
                //     label: '所属分公司',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2
                //     }
                // },
                // {
                //     type: SelectProject,
                //     keyName: 'projectId',
                //     label: '所属项目',
                //     disabled: true,
                //     attrs: {
                //         isDefaultSelected: this.editModel == 2,
                //         autoSelected: this.editModel == 2,
                //         keyValue: 'branchCompanyId',
                //         isClear: this.editModel == 2,
                //         isEdit: this.editModel != 2,
                //         form: this.form
                //     }
                // },
                {
                    keyName: 'floorName',
                    type: 'BaseInput',
                    disabled: this.editModel == 0,
                    label: '工程部位'
                },
                {
                    keyName: 'projectType',
                    type: SelectProjectType, 
                    disabled: this.editModel == 0,
                    label: '工程类别',
                    attrs:{
                        id:this.form.projectId,
                        defaultCheck:this.editModel==2,
                        init:false
                    },
                    change: () => {
                     this.$set(this.form, 'subItemProjectId',null);
                     this.$set(this.form, 'subItemProjectName',null)
                    },
                },
                {
                    keyName: 'subItemProjectId',
                    type: SelectTreeSubItem,
                    disabled: this.editModel == 0,
                    label: '分部分项',
                    attrs: {
                        typeId: this.form.projectType,
                        fatherDisabled: true
                    },
                    change:(value, labels)=>{
                        this.$set(this.form, 'subItemProjectName',labels[0])
                    }
                  },
                {
                    keyName: 'programmeNameId',
                    type: 'a-select',
                    data: this.programList,
                    disabled: this.editModel == 0,
                    label: '方案名称',
                    change:(val)=>{
                       this.getProgrammeName(val)
                    }
                },
                {
                    keyName: 'quantities',
                    type: 'BaseInput',
                    disabled: this.editModel == 0,
                    precision: 2,
                    label: '工程量'
                },
                {
                    type: SelectSubcontractor,
                    keyName: 'subcontractorId',
                    label: '分包单位',
                    disabled: this.editModel == 0,
                    attrs: {
                        isClear: this.editModel == 2,
                        isEdit: this.editModel != 2,
                        form: this.form,
                        projectId:this.editModel == 2?this.form.projectId:null,
                    },
                    selectChange: (e, b) => {
                     this.$set(this.form, 'subcontractorLeaderId',null)
                  },
                  getOption:(e,b)=>{
                    this.subContractorOrgId = e?.subContractorOrgId
                  }
                },
                {
                    label: '分包负责人',
                    keyName: 'subcontractorLeaderId',
                    type: SelectPersonByProject,
                    disabled: this.editModel == 0,
                    attrs: {
                        isOrg: true,
                        orgId: this.subContractorOrgId,
                        showSearch: true,
                        isEdit: true
                    }
                },
                {
                    keyName: 'disclosureTime',
                    type: 'a-date-picker',
                    disabled: this.editModel == 0,
                    label: '交底时间',
                    attrs: {
                        valueFormat: 'YYYY-MM-DD'
                    }
                },
                {
                    keyName: 'disclosureUserId',
                    type: ASelectOrgPeople,
                    disabled: this.editModel == 0,
                    label: '交底人',
                    attrs: {
                        orgId: this.SelectOrgId,
                        init:false,
                        isCreatorName:true
                    },

                },
                {
                    keyName: 'disclosureContent',
                    type: 'BaseTextarea',
                    label: '交底内容简述',
                    disabled: this.editModel == 0,
                    span: 24
                },

                {
                    slot: true,
                    keyName: 'fileInfoVOSigns',
                    label: '交底原件',
                    span: 24
                },
                {
                    slot: true,
                    keyName: 'fileInfoVOPictures',
                    label: '会议照片',
                    span: 24
                }
            ]
        }
    },
    methods: {
      getProgrammeName(val){
         let findData = this.programList.find((item)=>item.id == val);
        findData && this.$set(this.form,'version',findData.versionNumber)
         findData && this.$set(this.form,'programmeName',findData.label)
      },
      selectOrg(val) {
        this.form.projectId = val[val.length - 1].projectId
        this.form.branchCompanyId = val[val.length - 2].orgId ?? val[val.length - 1].orgId
        this.SelectOrgId = val[val.length - 1].orgId;
        
        //监听 项目查询方案名称数据
        if(this.editModel!=1){
            this.getProgramList(this.form.projectId,true);
            this.$set(this.form, 'subItemProjectId',null)
            this.$set(this.form, 'subItemProjectName',null)
            this.$set(this.form, 'disclosureUserId',null)
            this.$set(this.form, 'subcontractorLeaderId',null)
            this.$set(this.form, 'subcontractorName',null)
            this.$set(this.form, 'subcontractorId',null)
        }
      },
    //获取方案名称
    getProgramList(val,flag) {
        //清空方案名称,这样清空，下拉框好出现提示
        if(flag){
            delete this.form.programmeNameId
            delete this.form.programmeName
        }
        let param = {id:val}
        getProgramList(param).then((res) => {
         if (res.code == 200) {
          this.programList = res.data.map((v) => {
            v.label = v.schemeName
            v.value = v.id
            return v
          })
        }
      })
    },
        /**
         * 输入框事件
         */
        getOption(e, data) {
            if (e == 'subcontractorId') {
                this.subContractorOrgId = data?.subContractorOrgId
            }
        },
        validateForm() {
            let flag = false
            this.$refs.ruleForm.validate((e) => {
                if (e) {
                    flag = true
                }else {
                  this.$message.warning('请填写完所有必填项信息')
                }
            })
            return flag
        },
        /**
         * 提交表单
         */
        handleSubmit(status) {
            let that = this
            if (status == 'SUBMITTED') {
                if (!this.validateForm()) {
                    return
                }
            }

            // 提交表单
            that.loading = true
            that.loadingBtn[status] = true
            that.form.draftStatus = status == 'SUBMITTED' ? '0' : '1'

            let form = that.$clone(that.form)
            form.technicalDisclosurePictures = form.fileInfoVOPictures?.map((i) => i.commonId)
            form.technicalDisclosureSigns = form.fileInfoVOSigns?.map((i) => i.commonId)
            let api = [updateTechnicalDisclosure, addTechnicalDisclosure][that.editModel - 1] // 根据操作切换url地址

            console.log('formformformformformformformformform',form)
            api(form)
                .then(() => {
                    that.loading = false
                    that.loadingBtn[status] = false
                    that.$message.success(status == 'SUBMITTED' ? '提交成功！' : '保存成功')
                    that.$multiTab.close()
                })
                .catch(() => {
                    that.loadingBtn[status] = false
                    that.loading = false
                })
        }
    }
}
</script>

<style lang="less" scoped>
/deep/.ant-input {
border-color: #e4ac0b;
background-color: #fff9e8;
}
/deep/.ant-input-disabled
  {
    border-color: #d9d9d9 !important;
  background-color: #f5f5f5 !important;
  }
  
/deep/ .ant-form-item {
    .ant-form-item-label {
        height: 28px;
        width: 200px;
        line-height: 22px;
        padding: 6px 4px 0 0;
        text-align: right;
        white-space: pre-wrap;
        overflow: visible;
    }
    .ant-form-item-control-wrapper {
        width: calc(100% - 200px);
    }
}
.file_prompt {
    color: #999;
}
</style>
